package com.henry.extension.logging;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.AbstractConfiguration;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.xml.XmlConfiguration;
import org.w3c.dom.Element;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

public class MyLogManager {
    private static final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    private static final XmlConfiguration config = (XmlConfiguration)ctx.getConfiguration();

    public static void main(String[] args){
        try {
            Method method = config.getClass().getDeclaredMethod("constructHierarchy", Node.class, Element.class);
            Field rootElement = config.getClass().getDeclaredField("rootElement");
            method.invoke(config, config.getRootNode(), rootElement);

        } catch (Exception e) {

        }
//        config.
        Node rootNode = config.getRootNode();
        List<Node> nodes = rootNode.getChildren();
        for (Node node : nodes) {
            if (node.getName().equalsIgnoreCase("Loggers")) {
                List<Node> nodeList = node.getChildren();
                for (Node child : nodeList) {
                    Map<String, String> attributes = child.getAttributes();
                    if(attributes.get("name").equalsIgnoreCase("services")){
                        attributes.put("name","xxx");
                        config.createConfiguration(child, null);
                    }
                }
            }
            if (node.getName().equalsIgnoreCase("Appenders")) {

            }
        }
    }
}
